/*
 * Copyright 2014-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
<template>
  <div class="main-wrapper">
    <div id="shade" v-if="accountStatus === '1'"></div>
    <div id="reset-password" v-if="accountStatus === '1'">
      <div class="reset-password-title">
        {{ $t("main.changePassword") }}
      </div>
      <el-form
        :model="rulePasswordForm"
        status-icon
        :rules="rules2"
        ref="rulePasswordForm"
        label-width="148px"
        class="demo-ruleForm"
      >
        <el-form-item :label="$t('main.oldPassword')" prop="oldPass">
          <el-input
            type="password"
            v-model="rulePasswordForm.oldPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('main.newPassword')" prop="pass">
          <el-input
            type="password"
            v-model="rulePasswordForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('main.confirmPassword')" prop="checkPass">
          <el-input
            type="password"
            v-model="rulePasswordForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('rulePasswordForm')"
            :loading="loading"
            >{{ $t("main.submit") }}</el-button
          >
          <el-button @click="resetForm('rulePasswordForm')">{{
            $t("main.reset")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <v-content-head
      :headTitle="$t('title.dataOverview')"
      @changGroup="changGroup"
    ></v-content-head>
    <div class="content">
      <div
        class="menu-wrapper header"
        :class="{ 'menu-show': menuShow, 'menu-hide': menuHide }"
      >
        <v-menu
          @sidebarChange="change($event)"
          :minMenu="show"
          ref="menu"
        ></v-menu>
      </div>
      <div
        class="view-wrapper"
        :class="{
          'view-show': menuShow,
          'view-hide': menuHide,
          'contentShow': contentShow,
          viewHide: menuHide && contentShow,
        }"
      >
        <router-view v-if="isRouterAlive" class="bg-f7f7f7"></router-view>
      </div>
      <nav-content></nav-content>
      <!-- <div class="tipContent"></div>
        <div class="tips">
        <i class="el-icon-info" style="cursor:pointer" @click="tipIfShow"></i>   
        </div> -->
    </div>
    <set-front
      :show="frontShow"
      v-if="frontShow"
      @close="closeFront"
    ></set-front>
    <set-config
      :show="configShow"
      v-if="configShow"
      @close="closeConfig"
    ></set-config>
    <v-guide :show="guideShow" v-if="guideShow" @close="closeGuide"></v-guide>
  </div>
</template>

<script>
import sidebar from "./sidebar";
import setFront from "./dialog/setFront";
import setConfig from "./dialog/setConfig";
import guide from "./dialog/guide";
import contentHead from "@/components/contentHead";
import {
  resetPassword,
  addnodes,
  getGroups,
  encryption,
  getGroupsInvalidIncluded,
  getFronts,
  getChainInfo,
  getVersion,
} from "@/util/api";
import router from "@/router";
const sha256 = require("js-sha256").sha256;
import utils from "@/util/sm_sha";
import Bus from "@/bus";
import NavContent from "../../components/navs/navContent.vue";
export default {
  name: "mains",
  components: {
    "v-menu": sidebar,
    "set-front": setFront,
    "v-guide": guide,
    "set-config": setConfig,
    "v-content-head": contentHead,
    "nav-content": NavContent,
  },
  data() {
    return {
      guideShow: false,
      frontShow: false,
      menuShow: true,
      menuHide: false,
      loading: false,
      accountStatus: 0,
      account: localStorage.getItem("user"),
      frontData: [],
      rulePasswordForm: {
        oldPass: "",
        pass: "",
        checkPass: "",
      },
      configType: 1,
      configShow: false,
      tipShow: false,
      contentShow: false,
      isRouterAlive: true
    };
  },
  computed: {
    show: function () {
      return this.menuShow;
    },
    rules2() {
      var validatePass = (rule, value, callback) => {
        if (value === "") {
          callback(new Error(this.$t("main.inputPassword")));
        } else {
          if (this.rulePasswordForm.checkPass !== "") {
            this.$refs.rulePasswordForm.validateField("checkPass");
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === "") {
          callback(new Error(this.$t("main.againPassword")));
        } else if (value !== this.rulePasswordForm.pass) {
          callback(new Error(this.$t("main.passwordError")));
        } else {
          callback();
        }
      };
      let data = {
        oldPass: [
          {
            required: true,
            message: this.$t("main.inputOldPassword"),
            trigger: "blur",
          },
          {
            min: 6,
            max: 12,
            message: this.$t("main.longPassword"),
            trigger: "blur",
          },
        ],
        pass: [
          {
            required: true,
            validator: validatePass,
            trigger: "blur",
          },
          {
            min: 6,
            max: 12,
            message: this.$t("main.longPassword"),
            trigger: "blur",
          },
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,12}$/,
            message: this.$t("main.passwordPattern"),
            trigger: "blur",
          },
        ],
        checkPass: [
          {
            required: true,
            validator: validatePass2,
            trigger: "blur",
          },
          {
            min: 6,
            max: 12,
            message: this.$t("main.longPassword"),
            trigger: "blur",
          },
        ],
      };
      return data;
    },
  },
  mounted() {
    this.getEncryption();
    this.getConfigList();
    console.log(1);
    this.contentShow=false;
    let that = this;
    Bus.$on("navIfShow", () => {
      console.log(that.contentShow);
      that.contentShow = !that.contentShow;
    });
      Bus.$on("closeNav", () => {
      that.contentShow = false
    });
  },
  methods: {
    reload() {
     this.isRouterAlive = false
     this.$nextTick(() => (this.isRouterAlive = true))
   },
    tipIfShow() {
      this.tipShow = !this.tipShow;
    },
    changGroup(val) {
      this.groupId = val;
      this.reload()
    },
    getNetworkDetails: function () {
      this.loadingNumber = true;
      let groupId = this.groupId;
      getNetworkStatistics(groupId)
        .then((res) => {
          this.loadingNumber = false;
          if (res.data.code === 0) {
            this.detailsList.forEach(function (value, index) {
              for (let i in res.data.data) {
                if (value.name === i) {
                  value.value = res.data.data[i];
                }
              }
            });
          } else {
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    getChart: function () {
      this.loadingCharts = true;
      this.chartStatistics.show = false;
      this.chartStatistics.date = [];
      this.chartStatistics.dataArr = [];
      let groupId = localStorage.getItem("groupId");
      getChartData(groupId)
        .then((res) => {
          this.loadingCharts = false;
          if (res.data.code === 0) {
            let resData = changWeek(res.data.data);
            for (let i = 0; i < resData.length; i++) {
              this.chartStatistics.date.push(resData[i].day);
              this.chartStatistics.dataArr.push(resData[i].transCount);
            }
            this.$set(this.chartStatistics, "show", true);
          } else {
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    getNodeTable: function () {
      this.loadingNodes = true;
      let groupId = localStorage.getItem("groupId");
      let reqData = {
          groupId: groupId,
          pageNumber: 1,
          pageSize: 100,
        },
        reqQuery = {},
        reqParam = {
          groupId: groupId,
          pageNumber: 1,
          pageSize: 100,
        };
      this.$axios
        .all([getNodeList(reqData, reqQuery), getConsensusNodeId(reqParam)])
        .then(
          this.$axios.spread((acct, perms) => {
            this.loadingNodes = false;
            if (acct.data.code === 0 && perms.data.code === 0) {
              var nodesStatusList = acct.data.data,
                nodesAuthorList = perms.data.data;
              var nodesStatusIdList = nodesStatusList.map((item) => {
                return item.nodeId;
              });
              this.nodeData = [];
              nodesAuthorList.forEach((item, index) => {
                if (item.nodeType != "remove") {
                  nodesStatusList.forEach((it) => {
                    if (nodesStatusIdList.includes(item.nodeId)) {
                      if (item.nodeId === it.nodeId) {
                        this.nodeData.push(Object.assign({}, item, it));
                      }
                    } else {
                      this.nodeData.push(item);
                    }
                  });
                }
              });
              this.nodeData.forEach((item) => {
                if (item.nodeType === "observer") {
                  item.pbftView = "--";
                }
              });
              this.nodeData = unique(this.nodeData, "nodeId");
            } else {
              this.nodeData = [];
            }
          })
        );
    },
    getBlockList: function () {
      this.loadingBlock = true;
      let groupId = localStorage.getItem("groupId");
      let reqData = {
          groupId: groupId,
          pageNumber: 1,
          pageSize: 6,
        },
        reqQuery = {};
      getBlockPage(reqData, reqQuery)
        .then((res) => {
          this.loadingBlock = false;
          if (res.data.code === 0) {
            this.blockData = res.data.data;
          } else {
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    getTransaction: function () {
      this.loadingTransaction = true;
      let groupId = localStorage.getItem("groupId");
      let reqData = {
          groupId: groupId,
          pageNumber: 1,
          pageSize: 6,
        },
        reqQuery = {};
      getTransactionList(reqData, reqQuery)
        .then((res) => {
          this.loadingTransaction = false;
          if (res.data.code === 0) {
            this.transactionList = res.data.data;
          } else {
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    getConfigList: function () {
      getChainInfo()
        .then((res) => {
          if (res.data.code === 0) {
            if (res.data.data) {
              localStorage.setItem("configData", res.data.data.chainStatus);
            } else {
              localStorage.setItem("configData", 0);
            }
            this.getFrontTable();
          } else {
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    getVersionList() {
      getVersion()
        .then((res) => {
          if (res.status == 200) {
            this.$store.dispatch("set_mgr_version_action", res.data);
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    versionChange: function () {
      this.$refs.menu.changeRouter();
    },
    change: function (val) {
      this.menuShow = !val;
      this.menuHide = val;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.getResetPassword();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getResetPassword() {
      let reqData;
      reqData = {
        oldAccountPwd: sha256(this.rulePasswordForm.oldPass),
        newAccountPwd: sha256(this.rulePasswordForm.pass),
      };
      resetPassword(reqData, {})
        .then((res) => {
          this.loading = false;
          if (res.data.code === 0) {
            this.$message({
              type: "success",
              message: this.$t("main.updatePsdSuccess"),
            });
            this.accountStatus = "2";
            sessionStorage.setItem("accountStatus", this.accountStatus);
          } else {
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    getConfigData: function () {},
    getFrontTable() {
      let reqData = {
        // frontId: this.frontId
      };
      getFronts(reqData)
        .then((res) => {
          if (res.data.code === 0) {
            if (res.data.data.length > 0) {
              let num = 0;
              let versionKey;
              for (let i = 0; i < res.data.data.length; i++) {
                if (
                  res.data.data[i].clientVersion ||
                  res.data.data[i].supportVersion
                ) {
                  this.$store.dispatch(
                    "set_version_action",
                    res.data.data[i].clientVersion
                  );
                  this.$store.dispatch(
                    "set_support_version_action",
                    res.data.data[i].supportVersion
                  );
                  if (res.data.data[i].supportVersion) {
                    versionKey = res.data.data[i].supportVersion.substring(
                      2,
                      3
                    );
                    if (versionKey > 4) {
                      num++;
                    }
                  }
                }
              }
              if (num > 0) {
                localStorage.setItem("nodeVersionChange", 1);
              } else {
                localStorage.setItem("nodeVersionChange", "");
              }
              // if(localStorage.getItem("nodeVersionChange")){
              //     this.$emit("versionChange")
              // }
              this.accountStatus = sessionStorage.getItem("accountStatus");
              this.getVersionList();
              this.getGroupList();
              if (localStorage.getItem("nodeVersionChange")) {
                this.versionChange();
              }
            } else {
              this.accountStatus = sessionStorage.getItem("accountStatus");
              router.push("/host");
            }
          } else {
            router.push("/host");
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    getGroupList: function () {
      getGroupsInvalidIncluded()
        .then((res) => {
          if (res.data.code === 0) {
            if (res.data.data && res.data.data.length) {
              if (!localStorage.getItem("groupId")) {
                localStorage.setItem("groupId", res.data.data[0].groupId);
              }
              if (!localStorage.getItem("groupName")) {
                localStorage.setItem("groupName", res.data.data[0].groupName);
              }
              this.accountStatus = sessionStorage.getItem("accountStatus");
              if (this.$route.path && this.$route.path !== "/main") {
                router.push(this.$route.path);
              } else if (this.$route.path == "/main") {
                router.push("/home");
              } else {
                router.push("/home");
              }
            } else {
              // this.guideShow = true
            }
          } else {
            this.guideShow = false;
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
          router.push("/front");
          if (this.configType !== 1) {
            this.frontShow = true;
          } else {
            this.configShow = true;
          }
        });
    },
    // getFrontTable() {
    //     let reqData = {}
    //     getFronts(reqData)
    //         .then(res => {
    //             if (res.data.code === 0) {
    //                 let versionKey;
    //                 this.frontData = res.data.data || [];
    //                 let num = 0;
    //                 for(let i = 0; i < this.frontData.length; i++){
    //                     if(this.frontData[i].clientVersion){
    //                         versionKey = this.frontData[i].clientVersion.substring(2,3)
    //                         if(versionKey > 4 && !localStorage.getItem("nodeVersionChange")){
    //                             num ++
    //                         }
    //                     }
    //                 }
    //                 if(num > 0) {
    //                     localStorage.setItem("nodeVersionChange",1)
    //                 }else{
    //                     localStorage.setItem("nodeVersionChange","")
    //                 }
    //                 if(localStorage.getItem("nodeVersionChange")){
    //                     this.$refs.menu.changeRouter();
    //                 }
    //             } else {
    //                 this.$message({
    //                     message: this.$chooseLang(res.data.code),
    //                     type: "error",
    //                     duration: 2000
    //                 });

    //             }
    //         })
    //         .catch(err => {
    //             this.$message({
    //                 message: err.data || this.$t('text.systemError'),
    //                 type: "error",
    //                 duration: 2000
    //             });

    //         });
    // },
    getEncryption: function () {
      encryption()
        .then((res) => {
          if (res.data.code === 0) {
            if (res.data.data != localStorage.getItem("encryptionId")) {
              localStorage.removeItem("solcName");
              localStorage.removeItem("versionId");
            }
            localStorage.setItem("encryptionId", res.data.data);
          } else {
            this.$message({
              message: this.$chooseLang(res.data.code),
              type: "error",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err.data || this.$t("text.systemError"),
            type: "error",
            duration: 2000,
          });
        });
    },
    closeFront: function () {
      this.frontShow = false;
      this.getFrontTable();
    },
    closeConfig: function () {
      this.configShow = false;
      this.getFrontTable();
      Bus.$emit("changeConfig");
    },
    closeGuide: function () {
      this.guideShow = false;
      this.frontShow = true;
    },
  },
};
</script>
<style scoped>
.header .el-menu {
  height: 100%;
}
.main-wrapper {
  width: 100%;
  background: #f7f7f7;
  height: 100%;
}
.main-wrapper::after {
  display: block;
  content: "";
  clear: both;
}
.menu-wrapper {
  height: 96%;
  overflow-x: hidden;
  overflow-y: auto;
  z-index: 666;
  position: fixed;
  left: 0;
}
.view-wrapper {
  height: 100%;
  display: inline-block;
  overflow-y: scroll;
  position: relative;
  /* vertical-align: top; */
}
.contentShow {
  width: calc(100% - 520px) !important;
}
.viewHide {
  width: calc(100% - 376px) !important;
}
.menu-show {
  width: 200px;
  display: inline-block;
  transition: width 0.5s;
  -moz-transition: width 0.5s;
  -webkit-transition: width 0.5s;
  -o-transition: width 0.5s;
}
.menu-hide {
  width: 56px;
  /* width: 56px; */
  display: inline-block;
  transition: width 0.5s;
  -moz-transition: width 0.5s;
  -webkit-transition: width 0.5s;
  -o-transition: width 2s;
}
.view-show {
  padding-left: 200px;
  width: calc(100% - 200px);
  transition: width 0.5s;
  -moz-transition: width 0.5s;
  -webkit-transition: width 0.5s;
  -o-transition: width 0.5s;
}
.view-hide {
  width: calc(100% - 56px);
  padding-left: 56px;
  transition: width 0.5s;
  -moz-transition: width 0.5s;
  -webkit-transition: width 0.5s;
  -o-transition: width 2s;
}
.viewHide {
  /* width: calc(100% - 56px); */
}
#shade {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  /*兼容IE8及以下版本浏览器*/
  filter: alpha(opacity=30);
}

#reset-password {
  position: absolute;
  z-index: 3;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 470px;
  height: 273px;
  margin: auto;
  background-color: #fff;
  padding-top: 15px;
  /* padding-right: 25px; */
}
.reset-password-title {
  margin-bottom: 5px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}
#add-nodes {
  position: absolute;
  z-index: 3;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 470px;
  height: 140px;
  margin: auto;
  background-color: #fff;
  padding-top: 15px;
}
.add-nodes-title {
  margin-bottom: 5px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}
.demo-ruleForm {
  padding-right: 25px;
}
.tips {
  display: inline-block;
  position: absolute;
  top: 10%;
}
.tips .el-icon-info {
  font-size: 20px;
}
.transition-box {
  margin-bottom: 10px;
  width: 200px;
  height: 100px;
  border-radius: 4px;
  background-color: #409eff;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}
.tipContent {
  background-color: gray;
  width: 8%;
  height: 100%;
  display: inline-block;
}
.content {
  width: 100%;
  height: calc(100vh - 56px);
  padding-top: 56px;
  display: flex;
}
</style>
